<?php

class PostWritingForm extends CFormModel
{
	public $operator;
	public $operator_id;
	public $topic_id;
	public $title;
	public $content;
	
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return NGWordForm the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('title,content,operator', 'required'),
			array('operator', 'validateOperator'),
			array('topic_id', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'operator' => Yii::t('app','Operator user to use'),
			'topic_id' => Yii::t('app','Bulletin board for the writing'),
			'title' => Yii::t('app','Title'),
			'content' => Yii::t('app','Content'),
		);
	}

	public function validateOperator($attribute, $params) {
		$val = $this->$attribute;
		$u = User::model()->findByAttributes(array('profile_id'=>$val));
		if (!$u) {
			$this->addError($attribute, Yii::t('app', 'Operator not exists'));
		}
	}
	
	public function writePost() {
		$u = User::model()->findByAttributes(array('profile_id'=>$this->operator));
		$p = new Post();
		$p->user_id = $u->id;
		$p->topic_id = $this->topic_id;
		$p->content = $this->content;
		$p->title = $this->title;
		$p->created_time = date('Y-m-d H:i:s');
		$p->created_by_operator = 1;
		$p->save();
	}
}